package cn.aspart.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("load user by username: {}", username);

        if ("admin".equalsIgnoreCase(username)) {
            // 创建用户权限列表
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

            // 创建 UserDetails 对象
            // 注意，密码通过 BCryptPasswordEncoder 进行加密获得
            // 正常情况下，密码从数据库查询
            String password = new BCryptPasswordEncoder().encode("123456");
            return new User(username, password, authorities);
        } else {
            throw new UsernameNotFoundException("user not found with username " + username);
        }
    }
}
